package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.order.OrderFeignClient;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author Administrator
 * @create 2020-06-01 10:03
 */
@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {


    @Autowired
    private AlipayService alipayService;
    @Autowired
    private PaymentInfoService paymentInfoService;

    //支付宝支付
    @ResponseBody //返回的是一个页面
    @GetMapping("/submit/{orderId}")
    public String submit(@PathVariable(name ="orderId") Long orderId){
        return  alipayService.submit(orderId);
    }

    //跳转成功页面 只需要返回一个字符串就行
    @GetMapping("/callback/return")
    public String callbackReturn(){
        return "redirect:" + AlipayConfig.return_order_url;
    }
    //异步加载：通知商家用户支付成功
    @PostMapping("/callback/notify")
    @ResponseBody
    public String callbackNotify(@RequestParam Map<String,String> paramMap) throws Exception {
        //将异步通知中收到的所有参数都存放到map中
        boolean signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
       if(signVerified){
           System.out.println(paramMap);
           if ("TRADE_SUCCESS".equals(paramMap.get("trade_status"))) {
               //更新支付信息表   四个字段
               paymentInfoService.paySuccess(paramMap);
           }else{
               return "failure";
           }
           return "success";
       }else {
           // TODO 验签失败则记录异常日志，并在response中返回failure.
           return "failure";
       }
    }

    //退钱
    //退钱
    @GetMapping("/refund/{outTradeNo}")
    @ResponseBody
    public Result refund(@PathVariable(name = "outTradeNo") String outTradeNo){
        alipayService.refund(outTradeNo);
        return Result.ok();
    }
}
